package base64_captcha

import (
	"image/color"
	"time"

	"gitee.com/huangxinbo/xcas/pkg/logger"
	"github.com/mojocn/base64Captcha"
	"github.com/redis/go-redis/v9"
)

// CaptchaService captcha service
type Captcha struct {
	logger *logger.Logger
	store  base64Captcha.Store
}

// NewCaptchaService creates captcha service instance
func NewCaptcha(logger *logger.Logger, redisClient *redis.Client) *Captcha {
	var store base64Captcha.Store

	if redisClient != nil {
		// Use Redis to store captcha
		store = NewRedisStore(redisClient, logger)
		logger.Info("Captcha service using Redis storage")
	} else {
		// Use memory to store captcha
		store = base64Captcha.NewMemoryStore(20240, 5*time.Minute)
		logger.Info("Captcha service using memory storage")
	}

	return &Captcha{
		logger: logger,
		store:  store,
	}
}

// GenerateCaptcha generates captcha
func (s *Captcha) GenerateCaptcha(captchaType string) (string, string, error) {
	var driver base64Captcha.Driver

	switch captchaType {
	case "digit":
		// Digital captcha
		driver = base64Captcha.NewDriverDigit(80, 240, 4, 0.7, 80)
	case "string":
		// String captcha
		driver = base64Captcha.NewDriverString(80, 240, 4, 70, 80, "1234567890abcdefghijklmnopqrstuvwxyz", &color.RGBA{}, nil, []string{})
	default:
		// Default to digital captcha
		driver = base64Captcha.NewDriverDigit(80, 240, 4, 0.7, 80)
	}

	captcha := base64Captcha.NewCaptcha(driver, s.store)

	// Generate captcha
	id, b64s, _, err := captcha.Generate()
	if err != nil {
		s.logger.Error("Generate captcha failed: " + err.Error())
		return "", "", err
	}

	return id, b64s, nil
}

// VerifyCaptcha verifies captcha
func (s *Captcha) VerifyCaptcha(captchaId, captchaValue string) bool {
	if captchaId == "" || captchaValue == "" {
		return false
	}

	// Verify captcha
	valid := s.store.Verify(captchaId, captchaValue, true)

	if valid {
		s.logger.Info("Captcha verification successful, ID: " + captchaId)
	} else {
		s.logger.Warn("Captcha verification failed, ID: " + captchaId)
	}

	return valid
}
